package eraserhead;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import xml.Message;
import client.ServerAccess;
import eraserhead.boundary.WelcomeForm;
import eraserhead.controller.MessageResponseController;
import eraserhead.controller.ServerAccessManager;
import eraserhead.xml.request.ConnectRequest;

/**
 * Launch the Client Application, some code get from When2Meet Source Code
 * @author zhaolongli
 * @author Michael Checca
 */
public class ClientLauncher {

	static String serverHost = "localhost";

	/**
	 * The sacred {@code public static void main} entry point.
	 * @param args Arguments to the program, currently being ignored
	 */
	public static void main(String[] args) {
		/* Main objects needed to launch a DecisionLines instance */
		WelcomeForm mg;
		ServerAccess sa;
		MessageResponseController handler;

		/* FIRST thing to do is register the protocol being used. */
		if (!Message.configure("decisionLines.xsd")) {
			System.exit(0);
		}

		/* Select server with -server option */
		String server = serverHost;
		for (int i = 0; i < args.length; i++) {
			if (args[i].equals("-server") && i < args.length)
				server = args[i+1];
		}
		System.out.println(String.format("Server: %s", server));

		/* Create server access and send connect request */
		sa = new ServerAccess(serverHost);
		ServerAccessManager.setAccess(sa);
		handler = new MessageResponseController();
		if (sa.connect(handler))
			ConnectRequest.send(sa);

		/* Create the main GUI */
		mg = new WelcomeForm();
		mg.setVisible(true);
		mg.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent we) {
				// make sure we disconnect from the server once the main window dies 
				System.out.println("Client Disconnected.");
				ServerAccessManager.getAccess().disconnect();
				ServerAccessManager.setAccess(null);
			}
		});
	}

} 
